package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.IntemInformation;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.PurchaseOrder;
import com.kang.pojo.PurchaseOrderItem;
import com.kang.pojo.ReturnRequest;
import com.kang.pojo.ReturnRequestItem;
import com.kang.pojo.Warehouse;
import com.kang.pojo.WarehouseOrder;
import com.kang.pojo.WarehouseOrder_iteminformation;
import com.kang.pojo.WarehousePoJo;
import com.kang.service.AssistService;
import com.kang.service.IntemInformationService;
import com.kang.service.ItemDetailService;
import com.kang.service.PurchaseOrderService;
import com.kang.service.UserService;
import com.kang.service.WarehouseService;
import com.kang.service.warehouseOrderService;
import com.kang.service.warehouseOrder_itemInformationService;
import com.kang.until.OtherRealizePDF;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.PurchaseAgentPage;
import com.vonechina.entity.page.PurchaseOrderPage;
import com.vonechina.entity.page.WareHouseOrderPage;

/**
 * 采购入库
 * 
 * @author ysq
 *
 */
@Controller
@RequestMapping("warehouseOrder")
@SessionAttributes({ "wareHouseOrderPage" })
public class WarehouseOrderContrlooer extends com.kang.controller.Controller {
	/**
	 * 采购入库服务
	 */
	@Resource
	private warehouseOrderService whos;
	/**
	 * 用户管理服务
	 */
	@Resource
	private UserService users;

	/**
	 * 物品服务
	 */
	@Resource
	private IntemInformationService iifs;
	/**
	 * 采购入库-物品服务
	 */
	@Resource
	private warehouseOrder_itemInformationService whos_iifs;
	/**
	 * 采购订单
	 */
	@Resource
	private PurchaseOrderService pcos;
	/**
	 * 仓库服务
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 物品批次服务
	 */
	@Resource
	private ItemDetailService itemDetailService;
	/**
	 * 通用服务
	 */
	@Resource
	private AssistService assistService;

	/**
	 * 根据purchaseordereid删除WarehouseOrder
	 * 
	 * @param purchaseordereid
	 * @return
	 */
	@RequestMapping("delWarehouseOrder")
	@ResponseBody
	public String delWarehouseOrder(Integer purchaseordereid) {
		AjaxResult result = new AjaxResult();
		// 根据purchaseordereid删除WarehouseOrder
		int a = whos.delWarehouseOrder(purchaseordereid);

		// 查询WarehouseOrder_iteminformation数据根据warehouseOrderID
		List<WarehouseOrder_iteminformation> list1 = whos_iifs
				.selectWarehouseOrder_iteminformationByPurchaseordereid(purchaseordereid);
		// 修改purchaseorder_iteminformation状态
		for (int i = 0; i < list1.size(); i++) {

			// 修改purchaseorder_iteminformation采购订单-物品表的状态
			PurchaseOrderItem poi1 = new PurchaseOrderItem();
			poi1.setId(list1.get(i).getSourceID());
			poi1.setStatus("0");// 状态0=未处理，1=处理中，2=已处理
			pcos.updatePurchaseorder_iteminformationById(poi1);
		}
		// 根据id删除WarehouseOrderID
		int b = whos_iifs.deleteByWarehouseOrderID(purchaseordereid);

		if (a > 0 && b > 0) {
			result.setResult("success");
		} else {
			result.setResult("fail");
		}

		return JSON.toJSONString(result);
	}

	/**
	 * 去到查看采购入库详情
	 * 
	 * @param model
	 * @param purchaseordereid
	 * @return
	 */
	@RequestMapping("toDetailsWarehouseorder")
	public String toDetailsWarehouseorder(Model model, int purchaseordereid) {
		WarehouseOrder wo1 = whos.selectonePurchaseOrder(purchaseordereid);// 查询普通入库信息
		// 查询WarehouseOrder_iteminformation数据根据warehouseOrderID
		List<WarehouseOrder_iteminformation> list1 = whos_iifs
				.selectWarehouseOrder_iteminformationByPurchaseordereid(purchaseordereid);
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		int list1Sum = list1.size();
		for (int i = 0; i < list1Sum; i++) {
			// 查询物品信息根据inteminformationid
			IntemInformation iif1 = iifs.selectByID(list1.get(i)
					.getItemInformationID());

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("IntemInformation", iif1);
			map1.put("WarehouseOrder_iteminformation", list1.get(i));

			list2.add(map1);
		}

		model.addAttribute("wo1", wo1);
		model.addAttribute("list2", list2);

		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库

		model.addAttribute("buyerPerson",
				users.getUserById(wo1.getBuyerid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("createPerson",
				users.getUserById(wo1.getCreatepersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastperson",
				users.getUserById(wo1.getLastpersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		return "storage/purchaseWarehous/detailsWarehouseorder";
	}

	/**
	 * 去到修改采购入库
	 * 
	 * @param session
	 * @param model
	 * @param purchaseordereid
	 * @return
	 */
	@RequestMapping("toUpdate")
	public String updateWarehouseorder(HttpSession session, Model model,
			int purchaseordereid) {
		initRight(session);
		if (checkRight("编辑全部采购入库") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("organizations", assistService.listOrganization());// 查询机构组织（表）
		model.addAttribute("cruiseList", assistService.listCruise());// 查询邮轮表

		WarehouseOrder wo1 = whos.selectonePurchaseOrder(purchaseordereid);// 根据purchaseOrdereID查询采购入库信息
		// 查询WarehouseOrder_iteminformation数据根据warehouseOrderID
		List<WarehouseOrder_iteminformation> list1 = whos_iifs
				.selectWarehouseOrder_iteminformationByPurchaseordereid(purchaseordereid);
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		int list1Sum = list1.size();
		for (int i = 0; i < list1Sum; i++) {
			// 查询物品信息根据inteminformationid
			IntemInformation iif1 = iifs.selectByID(list1.get(i)
					.getItemInformationID());

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("IntemInformation", iif1);
			map1.put("WarehouseOrder_iteminformation", list1.get(i));

			// 根据WarehouseOrder_iteminformation的id查询出sourceID，根据sourceID查询出purchaseorder_iteminformation的purchaseOrderID，根据purchaseOrderID查询出purchaseorder_iteminformation
			PurchaseOrder purchaseOrder3 = pcos.selectOrderById2(list1.get(i)
					.getId());
			map1.put("purchaseOrder3", purchaseOrder3);

			list2.add(map1);
		}

		model.addAttribute("wo1", wo1);
		model.addAttribute("list2", list2);

		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库
		model.addAttribute("buyerPerson",
				users.getUserById(wo1.getBuyerid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("createPerson",
				users.getUserById(wo1.getCreatepersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastperson",
				users.getUserById(wo1.getLastpersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		return "storage/purchaseWarehous/updateWarehouseorder";
	}

	/**
	 * 修改采购入库
	 * 
	 * @param wo1
	 * @param itemIds
	 * @param itemNumber
	 * @param expiryDate
	 * @param purchaseorderIteminformationId
	 * @param materialMaterial2
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updateWarehouseorder(WarehouseOrder wo1, Integer[] itemIds,
			Integer[] itemNumber, String[] expiryDate,
			String[] purchaseorderIteminformationId, String materialMaterial2) {
		wo1.setMaterialMaterial(Integer.parseInt(materialMaterial2));
		AjaxResult result = new AjaxResult();
		wo1.setCreatetime(new Date());
		wo1.setFinalprocessingtime(new Date());
		whos.updateByPrimaryKeySelective(wo1);// 修改采购入库信息

		// 查询WarehouseOrder_iteminformation数据根据warehouseOrderID
		List<WarehouseOrder_iteminformation> list1 = whos_iifs
				.selectWarehouseOrder_iteminformationByPurchaseordereid(wo1
						.getPurchaseordereid());
		// 修改purchaseorder_iteminformation状态
		for (int i = 0; i < list1.size(); i++) {

			// 修改purchaseorder_iteminformation采购订单-物品表的状态
			PurchaseOrderItem poi1 = new PurchaseOrderItem();
			poi1.setId(list1.get(i).getSourceID());
			poi1.setStatus("0");// 状态0=未处理，1=处理中，2=已处理
			pcos.updatePurchaseorder_iteminformationById(poi1);
		}
		// 根据id删除WarehouseOrderID
		whos_iifs.deleteByWarehouseOrderID(wo1.getPurchaseordereid());

		for (int i = 0; i < itemIds.length; i++) {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = new Date();
			try {
				date1 = sdf.parse(expiryDate[i]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			WarehouseOrder_iteminformation wi1 = new WarehouseOrder_iteminformation();
			wi1.setExpiryDate(date1);
			wi1.setWarehouseOrderID(wo1.getPurchaseordereid());

			wi1.setItemInformationID(itemIds[i]);

			wi1.setNumber(itemNumber[i]);
			wi1.setSourceID(Integer.parseInt(purchaseorderIteminformationId[i]));// purchaseorder_iteminformation的id主键
			if (wo1.getStatus().equals(0)) {
				wi1.setStatus(0);// 处理状态
			} else if (wo1.getStatus().equals(1)) {
				wi1.setStatus(1);// 处理状态
			}

			whos_iifs.insertone(wi1);// 保存采购入库-物品WarehouseOrder_iteminformation

			// 如果是提交状态那就提交以及更改库存

			if (wo1.getStatus().equals(1)) {
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				iifs.updateIntemInformationCurrentStock(i2);// 修改库存

				// 插入item_detail
				ItemDetail itemDetail1 = new ItemDetail();
				itemDetail1.setItemInformationID(itemIds[i]);
				itemDetail1.setBatchNumber(itemDetailService
						.generateBatchNumber());

				itemDetail1.setExpiryDate(date1);
				itemDetail1.setNumber(itemNumber[i]);
				itemDetail1.setWarehouseManagementID(wo1.getWarehouseid());
				itemDetail1.setStatus(0);// 0正常
				itemDetail1.setSource_type(1);// 入库类型 0普通入库 1采购入库
				itemDetail1.setSource_id(wi1.getId());
				itemDetailService.addItemDetail(itemDetail1);

				// 修改purchaseorder_iteminformation采购订单-物品表的状态
				PurchaseOrderItem poi1 = new PurchaseOrderItem();
				poi1.setId(new Integer(purchaseorderIteminformationId[i]));
				poi1.setStatus("2");// 状态0=未处理，1=处理中，2=已处理
				pcos.updatePurchaseorder_iteminformationById(poi1);
			} else if (wo1.getStatus().equals(0)) {
				// 修改purchaseorder_iteminformation采购订单-物品表的状态
				PurchaseOrderItem poi1 = new PurchaseOrderItem();
				poi1.setId(new Integer(purchaseorderIteminformationId[i]));
				poi1.setStatus("1");// 状态0=未处理，1=处理中，2=已处理
				pcos.updatePurchaseorder_iteminformationById(poi1);
			}
		}

		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 根据采购订单id查询出订单里面的物品
	 * 
	 * @param oldaddress
	 * @param purchaseOrderID
	 * @param purchaseordereid
	 * @return
	 */
	@RequestMapping("listAddItem2")
	@ResponseBody
	public String listAddItem2(Integer oldaddress, Integer purchaseOrderID,
			Integer purchaseordereid) {
		// 根据采购订单表id查询采购订单表
		PurchaseOrder purchaseOrder1 = pcos.selectOrderById(purchaseOrderID);

		// 查询出采购订单下的物品
		List<PurchaseOrderItem> list1 = pcos
				.selectPurchaseorderIteminformationByPurchaseOrderID2(
						purchaseOrderID, null);
		// 查寻出该订单下的处理中的status==1物品
		if (oldaddress != null && oldaddress == purchaseOrderID) {
			// 查询WarehouseOrder_iteminformation数据根据warehouseOrderID
			List<WarehouseOrder_iteminformation> list3 = whos_iifs
					.selectWarehouseOrder_iteminformationByPurchaseordereid(purchaseordereid);
			for (int i = 0; i < list3.size(); i++) {
				// 查询出采购订单-物品表
				PurchaseOrderItem poi2 = pcos
						.selectPurchaseorder_iteminformationById(list3.get(i)
								.getSourceID());
				list1.add(poi2);
			}
		}
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		int list1Sum = list1.size();
		if (list1 != null) {
			for (int i = 0; i < list1Sum; i++) {
				// 查询物品信息根据inteminformationid
				IntemInformation iif1 = iifs.selectByID(list1.get(i)
						.getItemInformationID());
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("IntemInformation", iif1);
				map1.put("purchaseorder_iteminformation", list1.get(i));
				map1.put("purchaseOrder1", purchaseOrder1);

				list2.add(map1);
			}
		}
		return JSON.toJSONString(list2);

	}

	/**
	 * 添加采购入库-获取采购订单
	 * 
	 * @param purchaseOrderPage
	 * @return
	 */
	@RequestMapping("listAddItem")
	@ResponseBody
	public String listAddItem(PurchaseOrderPage purchaseOrderPage) {
		if ("2".equals(purchaseOrderPage.getMaterialMaterial())) {
			purchaseOrderPage.setMaterialMaterial("IMPA物料");
		} else if ("1".equals(purchaseOrderPage.getMaterialMaterial())) {
			purchaseOrderPage.setMaterialMaterial("普通物料");
		}

		purchaseOrderPage.setPageSize(10);// 设置每页显示几条
		purchaseOrderPage.setRows(pcos.countPurchaseOrder2(purchaseOrderPage));// 查询总行数
		List<PurchaseOrder> list1 = pcos.listPurchaseOrder2(purchaseOrderPage);// 查询数据
		AjaxResult result = new AjaxResult();
		result.setRows(list1);
		result.setTotal(purchaseOrderPage.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 去到添加采购入库
	 * 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("toAdd")
	public String addGeneralStorage(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增采购入库") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询可用仓库
		return "storage/purchaseWarehous/addWarehouseorder";
	}

	/**
	 * 添加采购入库
	 * 
	 * @param wo1
	 * @param itemIds
	 * @param itemNumber
	 * @param expiryDate
	 * @param purchaseorderIteminformationId
	 * @param materialMaterial2
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addWarehouseOrders(WarehouseOrder wo1, Integer[] itemIds,
			Integer[] itemNumber, String[] expiryDate,
			String[] purchaseorderIteminformationId, String materialMaterial2) {
		wo1.setMaterialMaterial(Integer.parseInt(materialMaterial2));
		AjaxResult result = new AjaxResult();
		wo1.setWarehousenumber(whos.selectMaxWarehouseNumber());// 生成采购入库编号
		wo1.setCreatetime(new Date());
		wo1.setFinalprocessingtime(new Date());

		whos.insertone(wo1);// 保存普通入库信息
		WarehouseOrder wo2 = whos.selectoneid(wo1.getWarehousenumber());// 根据采购入库单号查询采购入库信息
		if (wo2.getCreatepersonid() == null || wo2.getCreatepersonid() <= 0) {
			return JSON.toJSONString(result);
		}

		for (int i = 0; i < itemIds.length; i++) {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = new Date();
			try {
				date1 = sdf.parse(expiryDate[i]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			WarehouseOrder_iteminformation wi1 = new WarehouseOrder_iteminformation();
			wi1.setExpiryDate(date1);
			wi1.setWarehouseOrderID(wo2.getPurchaseordereid());

			wi1.setItemInformationID(itemIds[i]);

			wi1.setNumber(itemNumber[i]);
			wi1.setSourceID(Integer.parseInt(purchaseorderIteminformationId[i]));// purchaseorder_iteminformation的id主键
			if (wo2.getStatus().equals(0)) {
				wi1.setStatus(0);// 处理状态
			} else if (wo2.getStatus().equals(1)) {
				wi1.setStatus(1);// 处理状态
			}

			whos_iifs.insertone(wi1);// 保存采购入库-物品WarehouseOrder_iteminformation

			// 如果是提交状态那就提交以及更改库存

			if (wo2.getStatus().equals(1)) {
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				iifs.updateIntemInformationCurrentStock(i2);// 修改库存

				// 插入item_detail
				ItemDetail itemDetail1 = new ItemDetail();
				itemDetail1.setItemInformationID(itemIds[i]);
				itemDetail1.setBatchNumber(itemDetailService
						.generateBatchNumber());

				itemDetail1.setExpiryDate(date1);
				itemDetail1.setNumber(itemNumber[i]);
				itemDetail1.setWarehouseManagementID(wo2.getWarehouseid());
				itemDetail1.setStatus(0);// 0正常
				itemDetail1.setSource_type(1);// 入库类型 0普通入库 1采购入库
				itemDetail1.setSource_id(wi1.getId());
				itemDetailService.addItemDetail(itemDetail1);

				// 修改purchaseorder_iteminformation采购订单-物品表的状态
				PurchaseOrderItem poi1 = new PurchaseOrderItem();
				poi1.setId(new Integer(purchaseorderIteminformationId[i]));
				poi1.setStatus("2");// 状态0=未处理，1=处理中，2=已处理
				pcos.updatePurchaseorder_iteminformationById(poi1);
			} else if (wo2.getStatus().equals(0)) {
				// 修改purchaseorder_iteminformation采购订单-物品表的状态
				PurchaseOrderItem poi1 = new PurchaseOrderItem();
				poi1.setId(new Integer(purchaseorderIteminformationId[i]));
				poi1.setStatus("1");// 状态0=未处理，1=处理中，2=已处理
				pcos.updatePurchaseorder_iteminformationById(poi1);
			}
		}

		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 查询采购入库集合
	 * 
	 * @param session
	 * @param model
	 * @param wareHouseOrderPage
	 * @return
	 */
	@RequestMapping("selectByWhere")
	public String PurchaseorderSelectByWhere(HttpSession session, Model model,
			WareHouseOrderPage wareHouseOrderPage) {
		initRight(session);
		if (checkRight("查看采购入库") != SUCCESS
				&& checkRight("查看全部采购入库") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部采购入库") == SUCCESS) {
			wareHouseOrderPage.setSubnameId(null);
		} else {
			wareHouseOrderPage.setSubnameId(userID + "");
		}
		List<WarehousePoJo> who1 = whos.selectByWheres(wareHouseOrderPage);// 查询采购入库数据集合
		model.addAttribute("who1", who1);
		//System.out.println("=========查看采购入库list=============="+ who1.toString());
		List<Warehouse> wm = warehouseService.listAllWarehouse();// 仓库
		model.addAttribute("wm", wm);

		wareHouseOrderPage.setPageUrl("warehouseOrder/selectByWhere.do");
		model.addAttribute("page", wareHouseOrderPage);
		return "storage/purchaseWarehous/listPurchaseWarehous";
	}
	
	/**
	 * 导出采购入库PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, String warehousenumber, WareHouseOrderPage wareHouseOrderPage)
			throws Exception {
		WarehouseOrder warehouseOrder = whos.selectoneid(warehousenumber);
		List<WarehousePoJo> who1 = whos.selectByWheres(wareHouseOrderPage);// 查询采购入库数据集合
		//此方法为直接下载文件
		File file = StoragePDF.WarehouseOrderPDF(warehouseOrder, who1);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
}
